var express = require('express');
var router = express.Router();
require('./../util/util.js')
var User = require('./../models/user.js'); 

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('who are you');
});

router.get('/test',function(req,res,next){
	res.send('hahaha');
});

//注册接口
router.post('/register',function(req,res,next){
    var param = {
		userName:req.body.registerName,
        userPwd:req.body.registerPwd
    }
    User.findOne(param, function (err,doc){
        if(err){
            res.json({
                status:"1",
                msg:'err.message',
                result:''
            });
        }else{
            var userName2=doc.userName;
            if(userName==userName2){
                res.json({
                    status:'10',
                    msg:'账号已经被注册',
                    result:''
                })
            }else{
                //创建用户id
                var userplatform = '425';
                 r1 = Math.floor(Math.random()*10);
                 r2 = Math.floor(Math.random()*10);
                 sysDate = new Date().Format('yyyyMMddhhmmss');
                 createDate = new Date().Format('yyyy-MM-dd hh:mm:ss');
                 userId= userplatform + r1 +sysDate+r2;
                //创建用户信息
                var userInfo= {
                    userName:userName,
                    userPwd:userPwd,
                    userId:userId
                };
                User.create(userInfo,(err1,doc1) => {
                    if(err1){
                        res.json({
                           status:'11',
                           msg:'err1.message'
                        });
                    }else{
                        res.json({
                           status:'00',
                           msg:'注册成功',
                           result:'注册成功，请重新登录'
                        });
                    }
                })
            }  
}
})
})
//登录接口
router.post('/login',function(req,res,next){
	var param = {
		userName:req.body.userName,
		userPwd:req.body.userPwd
	}
    User.findOne(param,function(err,doc){
    	if(err){
    		res.json({
    			status:"1",
    			msg:err.message
    		});
    	}else{
            if(doc){
            	res.cookie("userId",doc.userId,{
            		path:'/',//放在根目录
            		maxAge:1000*60*60*24//单位位毫秒
            	});//cookie的名称，cookie的值，设定的参数
            	res.cookie("userName",doc.userName,{
            		path:'/',//放在根目录
            		maxAge:100*60*60//单位位毫秒
            	});
            	// req.session.user = doc;//也是一种存值
            	res.json({
            		status:"0",
            		msg:"",
            		result:{
            			userName:doc.userName
            		}
            	})
            }
    	}
    })
});

//登出接口
router.post("/logout",function(req,res,next){
	res.cookie("userId","",{
		path:'/',
		maxAge:-1
	});//清除cookie
	res.json({
		status:"0",
		msg:'',
		result:''
	})
})

//登录校验
router.get("/checkLogin",function(req,res,next){
	if(req.cookies.userId){
		res.json({
			status:'0',
			msg:'',
			result:req.cookies.userName
		});
	}else{
		res.json({
			status:'1',
			msg:'未登录',
			result:''
		})
	}
});

//查询挡车购物车的商品数量
router.get("/getCartCount",function(req,res,next){
    if(req.cookies && req.cookies.userId){
        let userId = req.cookies.userId;
        User.findOne({userId:userId},function(err,doc){
            if(err){
                res.json({
                    status:'1',
                    msg:err.message,
                    result:''
                });
            }else{
                if(doc){
                    var cartList = doc.cartList;
                    let cartCount = 0;
                    cartList.forEach((item)=>{
                        cartCount += parseInt(item.productNum);
                    });
                    res.json({
                        status:'0',
                        msg:'',
                        result:cartCount
                    })
                }
            }
        })
    }
})


//查询当前用户的购物车数据
router.get("/cartList",function(req,res,next){
    let userId = req.cookies.userId;
    User.findOne({userId:userId},function(err,doc){
        if(err){
            res.json({
                status:'1',
                msg:err.message,
                result:''
            });
        }else{
            if(doc){
                res.json({
                    status:'0',
                    msg:'',
                    result:doc.cartList
                });
            }
        }
    })  
});

//购物车删除
router.post("/cartDel",function(req,res,next){
    var userId = req.cookies.userId,
        productId = req.body.productId; 
    User.update({
      userId:userId
    },{
       $pull:{
          'cartList':{
               'productId':productId
           }
        }//在User表中找到对应的userId，删除cartList列表集合下条件为对应productId的一项
    },function(err,doc){
        if(err){
            res.json({
                status:'1',
                msg:err.message,
                result:''
            });
        }else{
            res.json({
                status:'0',
                msg:'',
                result:'suc'
            });
        }
    });
})

//修改购物车商品数量
router.post("/cartEdit",function(req,res,next){
    let userId = req.cookies.userId,
        productId = req.body.productId,
        productNum = req.body.productNum,
        checked = req.body.checked;
        console.log(checked);
    //更新数据库,{查找条件},{更新的数据}，回调函数
    User.update({
        "userId":userId,
        "cartList.productId":productId
    },{
        "cartList.$.productNum":productNum,
        "cartList.$.checked":checked  //商品是否选中
    },function(err,doc){
        if(err){
            res.json({
                status:'1',
                msg:err.message,
                result:''
            });
        }else{
            res.json({
                status:'0',
                msg:'',
                result:'suc'
            });
        }
    })
})

//修改购物车选中情况
router.post("/editCheckAll",function(req,res,next){
    let userId = req.cookies.userId,
        checkAll = req.body.checkAll?1:-1;
    User.findOne({userId:userId},function(err,user){
        if(err){
            res.json({
                status:'1',
                msg:err.message,
                result:''
            });
        }else{
            if(user){
                user.cartList.forEach((item)=>{
                    item.checked = checkAll;
                })
                user.save((err1,doc)=>{
                    if(err1){
                        res.json({
                           status:'1',
                           msg:err1.message,
                           result:''
                        });
                    }else{
                        res.json({
                           status:'0',
                           msg:'',
                           result:'suc'
                        });
                    }
                })
            }
        }
    }) 
});

//获取用户地址
router.get("/addressList",function(req,res,next){
    let userId = req.cookies.userId;
    User.findOne({userId:userId},function(err,user){
        if(err){
            res.json({
                status:"1",
                msg:err.message,
                result:''
            });
        }else{
            if(user){
                res.json({
                    status:"0",
                    msg:'',
                    result:user.addressList
                })
            }
        }
    })
})

//设置默认地址接口
router.post("/setDefault",function(req,res,next){
    let userId = req.cookies.userId,
        addressId = req.body.addressId;
    if(!addressId){
        res.json({
            status:'10003',
            msg:'地址不存在',
            result:''
        });
    }else{
        User.findOne({userId:userId},function(err,doc){
            if(err){
                res.json({
                    status:'10003',
                    msg:err.message,
                    result:''
                });
            }else{
                let addressList = doc.addressList;
                addressList.forEach((item)=>{
                    if(item.addressId == addressId){
                        item.isDefault = true;
                    }else{
                        item.isDefault = false;
                    }
                });
                doc.save(function(err1,doc1){
                    if(err1){
                        res.json({
                           status:'1',
                           msg:err1.message,
                           result:''
                        });
                    }else{
                        res.json({
                           status:'0',
                           msg:'',
                           result:'suc'
                        });
                    }
                })
            }
        }) 
    }   
});

//删除地址接口
router.post("/delAddress",function(req,res,next){
    let userId = req.cookies.userId,
        addressId = req.body.addressId;
    User.update({
        userId:userId
    },{
        $pull:{
            "addressList":{
                addressId:addressId
            }
        }
    },function(err,doc){
        if(err){
            res.json({
               status:'1',
               msg:err.message,
               result:''
            });
        }else{
            res.json({
               status:'0',
               msg:'',
               result:'suc'
            });
        }
    })
});

//生成订单
router.post("/payMent",function(req,res,next){
    let userId = req.cookies.userId,
        addressId = req.body.addressId,
        orderTotal = req.body.orderTotal;
    User.findOne({userId:userId},function(err,doc){
        if(err){
            res.json({
                status:'1',
                msg:'err.message',
                result:''
            });
        }else{
            if(doc){
                //获取当前用户的地址信息
                var address = '';
                doc.addressList.forEach((item)=>{
                    if(addressId == item.addressId){
                        address = item;
                    }
                });
                //获取当前用户购物车的商品信息
                var goodsList = [];
                doc.cartList.forEach((item)=>{
                    if(item.checked == '1'){
                        goodsList.push(item);
                    }
                });

                //创建订单Id
                var platform = '662';
                var r1 = Math.floor(Math.random()*10);
                var r2 = Math.floor(Math.random()*10);
                var sysDate = new Date().Format('yyyyMMddhhmmss');
                var createDate = new Date().Format('yyyy-MM-dd hh:mm:ss');
                var orderId = platform + r1 +sysDate+r2;

                //创建订单信息
                var order = {
                    orderId:orderId,
                    orderTotal:orderTotal,
                    addressInfo:address,
                    goodsList:goodsList,
                    orderStatus:'1',
                    createDate:createDate
                };
                doc.orderList.push(order);
                doc.save(function(err1,doc1){
                    if(err1){
                        res.json({
                           status:'1',
                           msg:'err1.message',
                           result:''
                        });
                    }else{
                        console.log(createDate);
                        res.json({
                           status:'0',
                           msg:'',
                           result:{
                               orderId:order.orderId,
                               orderTotal:order.orderTotal
                           }
                        });
                    }
                })
            }
        }
    }) 
});

//查询订单信息
router.get('/orderDetail',function(req,res,next){
    let userId = req.cookies.userId,
        orderId = req.param("orderId");
    User.findOne({userId:userId},function(err,userInfo){
        if(err){
            res.json({
                status:'1',
                msg:err.message,
                result:''
            });
        }else{
            var orderList = userInfo.orderList;
            if(orderList.length > 0){
                var orderTotal = 0;
                userInfo.orderList.forEach((item)=>{
                    if(item.orderId == orderId){
                        orderTotal = item.orderTotal;
                    }
                });
                res.json({
                    status:'0',
                    msg:'',
                    result:{
                        orderTotal:orderTotal,
                        orderId:orderId
                    }
                })
            }else{
                res.json({
                    status:'120001',
                    msg:'无此订单',
                    result:''
                });
            }
            
        }
    })
    
})

module.exports = router;
